<?php

namespace app\home\controller;

//引入公共控制器
use app\common\Controller\Home;

class Search extends Home
{
    public $NoLogin = ['search', 'details', 'likes', 'play'];

    protected $SubjectModel = null;
    protected $TeacherModel = null;
    protected $CategoryModel = null;
    protected $ChapterModel = null;
    protected $CommentModel = null;
    protected $OrderModel = null;
    protected $ReceiveModel = null;
    protected $RecordModel = null;
    protected $CommissionModel = null;


    public function __construct()
    {
        //继承父类的构造函数
        parent::__construct();

        //加载模型
        $this->SubjectModel = model('common/Subject/Subject');
        $this->TeacherModel = model('Teacher.Teacher');
        $this->CategoryModel = model('Subject.Category');
        $this->ChapterModel = model('Subject.Chapter');
        $this->CommentModel = model('Subject.Comment');
        $this->OrderModel = model('Subject.Order');
        $this->ReceiveModel = model('Coupon.Receive');
        $this->RecordModel = model('Business.Record');
        $this->BusinessModel = model('Business.Business');
        $this->CommissionModel = model('Business.Commission');
    }

    // 搜索
    public function search()
    {
        if ($this->request->isAjax()) {
            $keywords = $this->request->param('keywords', '', 'trim');
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');

            //偏移量
            $start = ($page - 1) * $limit;

            $where = [];

            if (!empty($keywords)) {
                $where['title'] = ['LIKE', "%$keywords%"];
            }

            //查询数据总条数
            $count = $this->SubjectModel->where($where)->count();

            //查询数据
            $list = $this->SubjectModel
                ->with(['category', 'teacher'])
                ->where($where)
                ->limit($start, $limit)
                ->select();

            $data = [
                'count' => $count,
                'list' => $list
            ];

            if ($list) {
                //成功返回
                $this->success('返回列表', null, $data);
                exit;
            } else {
                //失败返回
                $this->error('暂无数据', null, $data);
                exit;
            }
        }
        return $this->view->fetch();
    }

    // 课程详情页
    public function details()
    {
        $subid = $this->request->param('subid', 0, 'trim');

        // 判断课程信息是否存在
        $subject = $this->SubjectModel->with(['category'])->find($subid);

        if (!$subject) {
            $this->error('课程不存在');
            exit;
        }

        //给点赞状态设置一个属性嵌入到课程资料中
        $subject['likes_active'] = false;

        // 获取登录信息
        $login = $this->IsLogin(false);

        //判断是否已购买课程
        $buy = false;

        if ($login) {
            $likes = isset($subject['likes']) ? trim($subject['likes']) : '';
            $likes = explode(',', $likes);

            $collects = isset($subject['collects']) ? trim($subject['collects']) : '';
            $collects = explode(',', $collects);

            //增加一个自定义属性
            $subject['likes_active'] = in_array($login['id'], $likes) ? true : false;
            $subject['collects_active'] = in_array($login['id'], $collects) ? true : false;

            //查询当前用户是否有购买过
            $where = ['subid' => $subid, 'busid' => $login['id']];
            $check = $this->OrderModel->where($where)->find();
            $buy = $check ? true : false;
        }

        // 查询章节
        $chapter = $this->ChapterModel->where(['subid' => $subid])->select();

        // 查询评论
        // $comment = $this->CommentModel->where(['subid' => $subid])->select();

        // 老师信息
        $teacherid = isset($subject['teacherid']) ? trim($subject['teacherid']) : 0;
        $teacher = $this->TeacherModel->find($teacherid);

        if ($this->request->isAjax()) {
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');
            $keywords = $this->request->param('keywords', '', 'trim');

            //偏移量
            $start = ($page - 1) * $limit;

            $where = ['subid' => $subid];

            if (!empty($keywords)) {
                $where['content'] = ['LIKE', "%$keywords%"];
            }

            //查询数据总条数
            $count = $this->CommentModel->where($where)->count();

            //查询数据
            $list = $this->CommentModel
                ->with(['business'])
                ->where($where)
                ->order('id desc')
                ->limit($start, $limit)
                ->select();

            $data = [
                'count' => $count,
                'list' => $list
            ];

            if ($list) {
                //成功返回
                $this->success('返回列表', null, $data);
                exit;
            } else {
                //失败返回
                $this->error('暂无数据', null, $data);
                exit;
            }
        }

        // var_dump($subject->toArray());
        // exit;

        //赋值
        $this->assign([
            'subject' => $subject,
            'chapter' => $chapter,
            // 'comment' => $comment,
            'teacher' => $teacher,
            'buy' => $buy
        ]);

        return $this->view->fetch();
    }

    // 点赞功能
    public function likes()
    {
        if ($this->request->isAjax()) {
            $subid = $this->request->param('subid', 0, 'trim');

            $subject = $this->SubjectModel->find($subid);

            // 判断是否有登录
            $login = $this->IsLogin(false);

            if (!$login) {
                $this->error('请先登录');
                exit;
            }

            $likes = isset($subject['likes']) ? trim($subject['likes']) : '';
            $likes = explode(',', $likes);

            $action = $msg = '';

            // 如果用户ID在数组中就说明点过赞,不在就说明没有点赞
            // var_dump(in_array($login['id'], $likes));
            // exit;

            if (in_array($login['id'], $likes)) {
                // 已经点过赞，现在要取消点赞
                $key = array_search($login['id'], $likes);

                // 删除数组元素
                unset($likes[$key]);

                //取消动作
                $action = 'cancel';
                $msg = '取消点赞';
            } else {
                // 他没有点过赞，现在要点赞
                $likes[] = $login['id'];

                $action = 'active';
                $msg = '点赞';
            }
            $likes = array_filter($likes);  # 去空
            $likes = array_unique($likes);  # 唯一

            $data = [
                'id' => $subid,
                'likes' => implode(',', $likes)
            ];

            //更新语句
            $result = $this->SubjectModel->isUpdate(true)->save($data);

            if ($result === FALSE) {
                $this->error("{$msg}失败");
                exit;
            } else {
                $this->success("{$msg}成功", null, ['action' => $action]);
                exit;
            }
        }
    }

    // 收藏功能
    public function collects()
    {
        if ($this->request->isAjax()) {
            $subid = $this->request->param('subid', 0, 'trim');

            $subject = $this->SubjectModel->find($subid);

            // 判断是否有登录
            $login = $this->IsLogin(false);

            if (!$login) {
                $this->error('请先登录');
                exit;
            }

            $collects = isset($subject['collects']) ? trim($subject['collects']) : '';
            $collects = explode(',', $collects);

            $action = $msg = '';

            // 如果用户ID在数组中就说明点过赞,不在就说明没有点赞
            // var_dump(in_array($login['id'], $collects));
            // exit;

            if (in_array($login['id'], $collects)) {
                // 已经点过赞，现在要取消点赞
                $key = array_search($login['id'], $collects);

                // 删除数组元素
                unset($collects[$key]);

                //取消动作
                $action = 'cancel';
                $msg = '取消收藏';
            } else {
                // 他没有点过赞，现在要点赞
                $collects[] = $login['id'];

                $action = 'active';
                $msg = '收藏';
            }
            $collects = array_filter($collects);  # 去空
            $collects = array_unique($collects);  # 唯一

            $data = [
                'id' => $subid,
                'collects' => implode(',', $collects)
            ];

            //更新语句
            $result = $this->SubjectModel->isUpdate(true)->save($data);

            if ($result === FALSE) {
                $this->error("{$msg}失败");
                exit;
            } else {
                $this->success("{$msg}成功", null, ['action' => $action]);
                exit;
            }
        }
    }

    // 课程购买
    public function confirm()
    {
        $subid = $this->request->param('subid', 0, 'trim');

        //查询一下课程是否存在
        $subject = $this->SubjectModel->with(['category', 'teacher'])->find($subid);

        if (!$subject) {
            $this->error('课程不存在');
            exit;
        }

        //查询当前这个人领取过的优惠券
        $where = [
            'busid' => $this->view->AutoLogin['id'],
            'receive.status' => '1'
        ];

        $coupon = $this->ReceiveModel->with(['coupon'])->where($where)->select();

        // var_dump($subject->toArray());
        // exit;

        if ($this->request->isPost()) {
            $couid = $this->request->param('coupon', 0, 'trim');
            $pay = $this->request->param('pay', '', 'trim');

            $total = isset($subject['price']) ? trim($subject['price']) : 0;

            /**
             * subject_order 用户订单表
             * business_record 用户消费记录
             * business 用户表
             * coupon_receive 优惠券领取记录表
             */

            $this->OrderModel->startTrans();
            $this->RecordModel->startTrans();
            $this->BusinessModel->startTrans();
            $this->ReceiveModel->startTrans();
            $this->CommissionModel->startTrans();

            //查询是否有选择优惠券
            $where = ['receive.id' => $couid, 'receive.status' => '1'];
            $coupon = $this->ReceiveModel->with(['coupon'])->where($where)->find();

            if ($coupon) {
                //获取到折扣率
                $rate = isset($coupon['coupon']['rate']) ? trim($coupon['coupon']['rate']) : 1;

                //两个高精度数字相乘
                $total = bcmul($total, $rate);
            }

            //插入订单表
            $OrderData = [
                'subid' => $subid,
                'busid' => $this->view->AutoLogin['id'],
                'pay' => $pay,
                'total' => $total,
                'code' => build_code("ST"),
            ];

            //插入到订单表
            $OrderStatus = $this->OrderModel->validate('common/Subject/Order')->save($OrderData);

            if ($OrderStatus === FALSE) {
                $this->error($this->OrderModel->getError());
                exit;
            }

            //消费记录
            $title = $subject['title'];
            $content = "购买了【{$title}】,花费了￥ $total 元";
            $RecordData = [
                'total' => "-$total",
                'content' => $content,
                'busid' => $this->view->AutoLogin['id']
            ];

            $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);

            if ($RecordStatus === FALSE) {
                $this->OrderModel->rollback();
                $this->error($this->RecordModel->rollback());
                exit;
            }

            //如果是余额支付就需要更新用户余额字段
            if ($pay == "money") {
                //减去消费的金额 剩下的余额
                $money = bcsub($this->view->AutoLogin['money'], $total);

                $BusinessData = [
                    'id' => $this->view->AutoLogin['id'],
                    'money' => $money
                ];

                $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($BusinessData);

                if ($BusinessStatus === FALSE) {
                    $this->RecordModel->rollback();
                    $this->OrderModel->rollback();
                    $this->error('个人余额更新失败');
                    exit;
                }
            }

            //如果有选择优惠券那么就要更新优惠券使用状态
            if ($coupon) {
                $ReceiveData = [
                    'id' => $couid,
                    'status' => '0'
                ];

                $ReceiveStatus = $this->ReceiveModel->isUpdate(true)->save($ReceiveData);

                if ($ReceiveStatus === FALSE) {
                    $this->BusinessModel->rollback();
                    $this->RecordModel->rollback();
                    $this->OrderModel->rollback();
                    $this->error('优惠券状态更新失败');
                    exit;
                }
            }

            //判断是否有推荐人可以得到佣金
            $parentid = $this->view->AutoLogin['parentid'] ? trim($this->view->AutoLogin['parentid']) : 0;
            $parent = $this->BusinessModel->find($parentid);
            if ($parent) {
                //佣金比率
                $AmountRate = config('site.AmountRate');

                //消费金额*佣金比率 = 转给推荐人
                $amount = bcmul($total, $AmountRate);

                //插入佣金记录
                $CommissionData = [
                    'orderid' => $this->OrderModel->id, //获取插入最后一条的自增ID
                    'busid' => $this->view->AutoLogin['id'],
                    'parentid' => $parentid,
                    'type' => 'subject', //买课程的佣金
                    'stauts' => '0', //未提现
                    'amount' => $amount, //佣金
                ];

                $CommissionStatus = $this->CommissionModel->save($CommissionData);

                if ($CommissionStatus === FALSE) {
                    $this->ReceiveModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->RecordModel->rollback();
                    $this->OrderModel->rollback();
                    $this->error('推荐信息存储失败');
                    exit;
                }
            }

            if ($OrderStatus === FALSE || $RecordStatus === FALSE) {
                $this->CommissionModel->rollback();
                $this->ReceiveModel->rollback();
                $this->BusinessModel->rollback();
                $this->RecordModel->rollback();
                $this->OrderModel->rollback();
                $this->error('推荐信息存储失败');
                exit;
            } else {
                $this->OrderModel->commit();
                $this->RecordModel->commit();
                $this->BusinessModel->commit();
                $this->ReceiveModel->commit();
                $this->CommissionModel->commit();
                $this->success('购买课程成功', url('home/search/details', ['subid' => $subid]));
                exit;
            }
        }

        $this->assign([
            'subject' => $subject,
            'coupon' => json_encode($coupon)
        ]);

        return $this->view->fetch();
    }

    // 课程播放
    public function play()
    {
        if ($this->request->isAjax()) {
            $cid = $this->request->param('cid', 0, 'trim');

            //查询一下这个章节是否存在
            $chapter = $this->ChapterModel->find($cid);

            if (!$chapter) {
                $this->error('章节不存在');
                exit;
            }

            //判断是否有登录
            $login = $this->IsLogin(false);

            if (!$login) {
                $this->error('请先登录');
                exit;
            }

            //查找当前用户是否购买过订单
            $where = [
                'subid' => $chapter['subid'],
                'busid' => $login['id']
            ];

            $order = $this->OrderModel->where($where)->find();

            if (!$order) {
                $this->success('请先购买课程', null, ['action' => 'buy']);
                exit;
            }

            $this->success('返回章节的信息', null, ['action' => $chapter['url_text']]);
            exit;
        }
    }
}
